import requests
from xinfou1 import settings


def get_code(from_city, to_city):
    # 将参数放到字典里，之后可以直接在request.get中添加
    params = {
        'address' : from_city + '|' + to_city,
        'key' : settings.GAODE_KEY,
        'batch' : True
    }
    gd_url = "https://restapi.amap.com/v3/geocode/geo?"
    response = requests.get(url=gd_url, params=params)
    response = response.json()
    geocodes = response.get('geocodes')
    from_code = geocodes[0].get('location')
    to_code = geocodes[1].get('location')

    return from_code,to_code

def get_time(from_code, to_code):
    params = {
        'origins':from_code,
        'destination':to_code,
        'key':settings.GAODE_KEY
    }
    dis_url = 'https://restapi.amap.com/v3/distance?'
    response = requests.get(url=dis_url, params=params)
    response = response.json()
    result = response.get('result')
    time = result[0].get('duration')
    time = float(time) / 3600
    return time


def get_distance(from_city, to_city):
    origin_code, destination_code = get_code(from_city, to_city)
    time = get_time(origin_code, destination_code)
    return time